package com.ruoyi.system.coretools;

import com.ruoyi.common.core.domain.model.TransInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.TLangLibrary;
import com.ruoyi.system.mapper.TLangLibraryMapper;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class TranslateDriver {

    @Resource
    TLangLibraryMapper tLangLibraryMapper;

    @Autowired
    private RedisCache redisCache;

    private static String accessKeyId;

    private static String accessKeySecret;

    public TranslateDriver(){
        ISysConfigService configService= SpringUtils.getBean(ISysConfigService.class);
        this.accessKeyId=configService.selectConfigByKey("translate.ali.accessKeyId");
        this.accessKeySecret=configService.selectConfigByKey("translate.ali.accessKeySecret");
    }

    /**
     * 保存语言到语言池子（组合使用，后面有单独翻译的工具和单独保存的工具）
     *
     * @param transInfo
     * @throws Exception
     */
    public void saveLangPoolWapper(TransInfo transInfo) throws Exception {
        //翻译
        String result = callTranslate(transInfo.getSourceLanguage(), transInfo.getTargetLanguage(), transInfo.getSourceText());
        //保存
        saveLangPool(transInfo.getSourceText(), transInfo.getTargetLanguage(), result, 3);
    }

    /**
     * 获取语言池数据信息工具（最常用）（数据从redis获取）最常用
     *
     * @param code
     * @param langCode
     */
    public String getLangPoolByRedis(String code, String langCode) {
        //从redis获取
        String langValue = redisCache.getCacheMapValue("langPool", code + "_" + langCode);//同步到redis，双写。
        return langValue;
    }

    /**
     * 保存语言池数据工具
     *
     * @param code      //编码，可以是要翻译的文本或其他都行
     * @param langCode  //语言编码
     * @param langValue //要保持的翻译后的值
     * @param type      //要贴的标签
     */
    public void saveLangPool(String code, String langCode, String langValue, Integer type) {

        TLangLibrary tLangLibrary = new TLangLibrary();
        tLangLibrary.setCode(code);
        tLangLibrary.setLangCode(langCode);

        if (tLangLibraryMapper.selectTLangLibraryList(tLangLibrary).isEmpty()) {
            tLangLibrary.setTargetValue(langValue);
            if (null != type) {
                tLangLibrary.setType(type);//如果为空默认为其他
            }
            tLangLibraryMapper.insertTLangLibrary(tLangLibrary);
            redisCache.setCacheMapValue("langPool", code + "_" + langCode, langValue);//同步到redis，双写。
        }
    }


    /**
     * 获取语言池数据信息工具（备用）
     *
     * @param code
     * @param langCode
     * @param type     (可传入空)
     */
    public String getLangPool(String code, String langCode, Integer type) {
        TLangLibrary tLangLibrary = new TLangLibrary();
        tLangLibrary.setCode(code);
        tLangLibrary.setLangCode(langCode);
        if (type != null) {
            tLangLibrary.setType(type);//如果为空默认为其他
        }
        List<TLangLibrary> list = tLangLibraryMapper.selectTLangLibraryList(tLangLibrary);
        return !list.isEmpty() ? list.get(0).getTargetValue() : null;
    }


    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.alimt20181012.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "mt.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.alimt20181012.Client(config);
    }


    /**
     * 阿里语言翻译工具类
     *
     * @param sourceLanguage
     * @param targetLanguage
     * @param sourceText
     * @return
     * @throws Exception
     */
    public static String callTranslate(String sourceLanguage, String targetLanguage, String sourceText)  {
        //先写死后面在配置化"LTAI5t9xahx1yB7J9atYfQ4P", "YaYaPdiu89yKzUNtg9OFpFVGaq94ph"
        try {
        com.aliyun.alimt20181012.Client client = TranslateDriver.createClient(accessKeyId, accessKeySecret);
        com.aliyun.alimt20181012.models.TranslateGeneralRequest translateGeneralRequest = new com.aliyun.alimt20181012.models.TranslateGeneralRequest()
                .setFormatType("text")
                .setSourceLanguage(sourceLanguage)
                .setTargetLanguage(targetLanguage)
                .setSourceText(sourceText)//测试
                .setScene("general");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 复制代码运行请自行打印 API 的返回值
            com.aliyun.alimt20181012.models.TranslateGeneralResponse response = client.translateGeneralWithOptions(translateGeneralRequest, runtime);
            if (200 == response.getBody().getCode()) {
                return response.getBody().getData().getTranslated();
                //System.out.println(com.aliyun.teautil.Common.toJSONString(response));
                //return response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new UtilException("translate error");
        }

        return null;

    }


/*

 AccessKey ID
    LTAI5t9xahx1yB7J9atYfQ4P

    AccessKey Secret
    YaYaPdiu89yKzUNtg9OFpFVGaq94ph


    */


}
